//
//  MainViewController.m
//  Sight
//
//  Created by chen on 16/6/8.
//  Copyright (c) 2016年 chen. All rights reserved.
//

#import "ImageProViewController.h"
#import "FilteredImageCell.h"
#import <GPUImage/GPUImage.h>
#import  "BlurBackground.h"

#define kMainScreenWidth [UIScreen mainScreen].bounds.size.width
#define kMainScreenHeight [UIScreen mainScreen].bounds.size.height

@interface ImageProViewController()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,BlurBackgroundDelegate>

@property (strong,nonatomic) NSDictionary *FilterClassName;
@property (strong,nonatomic) UIView *menuView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong,nonatomic) UIImage *sourceImage;
@property (strong,nonatomic) UIImage *scaleImage;
@property (strong,nonatomic) GPUImageFilter *currenrFilter;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (strong,nonatomic) UIImageView *blurImageView;

@end

@implementation ImageProViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.FilterClassName = @{NSStringFromClass([GPUImageGammaFilter class]):@"灰度",
                             NSStringFromClass([GPUImageSepiaFilter class]):@"怀旧",
                             NSStringFromClass([GPUImageSketchFilter class]):@"素描",
                             NSStringFromClass([GPUImagePixellateFilter class]):@"像素化",
                             NSStringFromClass([GPUImageColorInvertFilter class]):@"反转",
                             NSStringFromClass([GPUImageToonFilter class]):@"卡通",
                             NSStringFromClass([GPUImageRGBErosionFilter class]):@"腐蚀",
                             NSStringFromClass([GPUImageFilter class]):@"正常"};
    
    // Do any additional setup after loading the view.
    self.sourceImage = [UIImage imageNamed:@"demo.jpg"];
    self.imageView.image = self.sourceImage;
    
    [self createMenuView];
    [self.menuView setHidden:YES];
    
    [self.imageView setUserInteractionEnabled:YES];
    UILongPressGestureRecognizer *imageLongPressGR=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(imageLongPressTick:)];
    [self.imageView addGestureRecognizer:imageLongPressGR];
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    
    NSLog(@"viewDidLoad");
}

-(void)imageLongPressTick:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state==UIGestureRecognizerStateBegan) {
    UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:@"分享" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"Save", nil];
        //actionSheet.actionSheetStyle=UIActionSheetStyleBlackOpaque;
        [[BlurBackground sharedBlurground]addBlurBackgroundToView:self.view.superview];
        [actionSheet showInView:self.imageView];
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        UIImageWriteToSavedPhotosAlbum(self.imageView.image, self,nil, nil);
    }
    [[BlurBackground sharedBlurground]removeBackgroundFromView];
}

- (void)createMenuView
{
    //Create main button
   
    
    //create menuView
    self.menuView=[[UIView alloc]initWithFrame:CGRectMake(10, self.navigationController.navigationBar.frame.size.height+25, self.view.frame.size.width-20, 80)];
    self.menuView.backgroundColor=[UIColor colorWithWhite:0.200 alpha:1.000];
    //create Buuton
    UIButton *album=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.menuView.frame.size.width/2.0, self.menuView.frame.size.height)];
    [album setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [album setTitle:@"打开相册" forState:UIControlStateNormal];
    [album addTarget:self action:@selector(albumBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    UIButton *camera=[[UIButton alloc]initWithFrame:CGRectMake(self.menuView.frame.size.width/2.0, 0, self.menuView.frame.size.width/2.0, self.menuView.frame.size.height)];
    [self.menuView addSubview:album];
    [camera setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [camera setTitle:@"拍照" forState:UIControlStateNormal];
    [camera addTarget:self action:@selector(cameraBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    UIButton *video=[[UIButton alloc]initWithFrame:CGRectMake(self.menuView.frame.size.width/2.0, 0, self.menuView.frame.size.width/2.0, self.menuView.frame.size.height)];
    [self.menuView addSubview:camera];

    //[self.view addSubview:self.menuView]; //此方法会被imageview遮掩
    //为了不被imageview窗口掩盖，添加到window
    [[[UIApplication sharedApplication].windows  lastObject]addSubview:self.menuView];
    
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"FilteredImageCell" bundle:nil] forCellWithReuseIdentifier:@"FilteredImageCell"];

}





- (IBAction)menuBtnPressed:(id)sender
{
    if ([self.menuView isHidden]) {
        self.menuView.hidden=NO;
        [[BlurBackground sharedBlurground]addBlurBackgroundToView:self.view.superview];
        
    }else{
        self.menuView.hidden=YES;
        [[BlurBackground sharedBlurground]removeBackgroundFromView];
    }

}




-(void)albumBtnPressed
{
    NSLog(@"album");
    self.menuView.hidden=YES;
    
    //打开相册
    UIImagePickerController *picker=[[UIImagePickerController alloc]init];
    picker.delegate=self;
    picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:^{NSLog(@"ok");}];
}

-(void)cameraBtnPressed
{
    NSLog(@"camera");
    self.menuView.hidden=YES;

}


-(void)videoBtnPressed
{
    NSLog(@"video");
    self.menuView.hidden=YES;
}


/**
 *  缩小图片
 *
 *  @param sourceImage 原图像，一般比较大
 *
 *  @return 缩小后的图像，按照collectionView的cell大小
 */

-(UIImage *) imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    
    if (sourceImage ==nil) {
        NSLog(@"imageCompressForSize:sourceImage is nil");
        return nil;
    }
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
            
        }
        else{
            
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma  mark - UICollectionView delegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.sourceImage ==nil) {
        return 0;
    }else
        return [self.FilterClassName count];

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",indexPath.item);
    FilteredImageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"FilteredImageCell" forIndexPath:indexPath];
    GPUImageFilter *filter = [[NSClassFromString([[self.FilterClassName allKeys]objectAtIndex:indexPath.item]) alloc]init];
    //图像缩放失败，暂时使用原图
    //UIImage *filteredimage = [filter imageByFilteringImage:self.scaleImage];
    UIImage *filteredimage = [filter imageByFilteringImage:self.sourceImage];
    cell.imageView.image = filteredimage;
    cell.filterName.text = [[self.FilterClassName allValues]objectAtIndex:indexPath.item];
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(80, self.collectionView.frame.size.height-self.collectionView.layoutMargins.top-self.collectionView.layoutMargins.bottom);
}


-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5,5,5,5);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    FilteredImageCell *cell=(FilteredImageCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor=[UIColor colorWithRed:37/255.0f green:175/255.0f blue:148/255.0f alpha:1.0f];
    self.imageView.image=cell.imageView.image;
}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    FilteredImageCell *cell=(FilteredImageCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor=[UIColor whiteColor];
}

#pragma mark - UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    self.sourceImage=[[info objectForKey:UIImagePickerControllerOriginalImage]copy];
    UICollectionViewCell *cell=[self.collectionView  cellForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    CGSize size= cell.frame.size;
    self.scaleImage = [self imageCompressForSize:self.sourceImage targetSize:size];
    self.imageView.image = self.sourceImage;
    
    [picker dismissViewControllerAnimated:NO completion:nil];
    
    [self.collectionView reloadData];
   
    
}

#pragma mark - BlurBackgroundDelegate
-(void)BlurBackgroundTapped{
    //背景被点击，移除菜单
    if (![[self.menuView superview] isEqual:[NSNull class]]) {
        [self.menuView removeFromSuperview];
    }
}

- (IBAction)goBackButtonPressed:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
